#define _CRT_SECURE_NO_WARNINGS 1
#include"heap.h"

void HeapInit(Heap* hp)
{
	assert(hp);

	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void HeapDestory(Heap* hp)
{
	assert(hp);

	free(hp->a);
	hp->a = NULL;
	hp->capacity = 0;
	hp->size = 0;
}

void Swap(HPDataType* p1, HPDataType* p2)
{
	HPDataType tmp = *p1;
	*p1 = *p2;
	*p2 = tmp;
}

void AdjustUp(HPDataType* p, int size)
{
	int parent = (size - 1) / 2;
	int child = size;
	while (child > 0)
	{
		if (p[child] < p[parent])
		{
			Swap(&p[child], &p[parent]);
			child = (child - 1) / 2;
			parent = (parent - 1) / 2;
		}
		else
		{
			break;
		}
	}
}

void AdjustDown(HPDataType* p,int size,int parent)
{
	int child = parent * 2 + 1;
	while (child < size)
	{
		if (child+1<size && p[child] > p[child + 1])
			child = child + 1;
		if (p[parent] > p[child])
		{
			Swap(&p[child], &p[parent]);
			parent = child;
			child = child * 2 + 1;
		}
		else
		{
			break;
		}
	}
}

void HeapPush(Heap* hp, HPDataType x)
{
	assert(hp);

	if (hp->capacity == hp->size)
	{
		int newcapacity = hp->capacity == 0 ? 4 : hp->capacity * 2;
		HPDataType* tmp = (HPDataType*)realloc(hp->a,sizeof(HPDataType) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc error");
			exit(-1);
		}
		hp->a = tmp;
		hp->capacity = newcapacity;
	}
	hp->a[hp->size] = x;
	hp->size++;
	AdjustUp(hp->a,hp->size-1);
}

void HeapPop(Heap* hp)
{
	if (hp->size == 1)
	{
		hp->size--;
		return 0;
	}
	assert(hp);
	assert(hp->size - 1 > 0);

	Swap(&hp->a[0], &hp->a[hp->size - 1]);
	hp->size--;
	AdjustDown(hp->a,hp->size,0);
}

HPDataType HeapTop(Heap* hp)
{
	assert(hp);
	assert(hp->size > 0);

	return hp->a[0];
}

int HeapSize(Heap* hp)
{
	assert(hp);

	return hp->size;
}

bool HeapEmpty(Heap* hp)
{
	assert(hp);

	return hp->size == 0;
}